import SparkMD5 from "spark-md5"
function calculateFileMD5(file, start, end, chunkSize, type) {
    return new Promise((resolve, reject) => {
        const spark = new SparkMD5.ArrayBuffer();
        const fileSize = file.size;
        const chunkCount = end;
        let currentChunk = start;
        let result = []
        function loadNextChunk() {
            const start = currentChunk * chunkSize;
            const end = Math.min(start + chunkSize, fileSize);
            const reader = new FileReader();
            const blob = file.slice(start, end);
            reader.onload = (e) => {
                spark.append(e.target.result); // 将当前分片加入 MD5 计算
                currentChunk++;
                if (type === "all") {
                    if (currentChunk < chunkCount) {
                        loadNextChunk(); // 继续加载下一个分片
                    } else {
                        result.push(spark.end())
                        resolve(result);
                    }
                } else {
                    if (currentChunk < chunkCount) {
                        loadNextChunk(); // 继续加载下一个分片
                        result.push(spark.end())
                    } else {
                        result.push(spark.end())
                        resolve(result);
                    }
                }

            };
            reader.onerror = reject;
            reader.readAsArrayBuffer(blob);
        }

        loadNextChunk(); // 开始加载第一个分片
    });
}
self.onmessage = function (event) {
    console.log(event);
    const { chunkSize, start, end, file, type } = event.data
    if (type === "all") {
        calculateFileMD5(file, 0, end, chunkSize, type).then(res => {
            self.postMessage(res);
        })
    } else {
        console.log(start, end);
        calculateFileMD5(file, start, end, chunkSize, type).then(res => {
            console.log(start, end);
            if (start === end) return
            self.postMessage(res);
        })
    }
}
